package demo.util;

import java.util.Scanner;

import org.apache.commons.lang3.time.DurationFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author roger.xu
 * 
 */
public class Console {
    private static final Log _log = LogFactory.getLog(Console.class.getSimpleName());

    private static Console instance = new Console();
    private static java.io.Console jvmConsole = System.console();
    private static long lastTimestamp = -1L;

    /**
     * Return a single Console instance.
     * 
     * @return console instance.
     */
    public static Console getInstance() {
        return instance;
    }

    public String getConsoleString(Object... args) {
        return BaseUtils.join(args);
    }

    public void debug(Object... args) {
        print(args);
    }

    /**
     * Log the time duration.
     */
    public void period() {
        period(null);
    }

    public void period(final String msg) {
        if (lastTimestamp == -1L) {
            lastTimestamp = System.currentTimeMillis();
        }

        final long currentTimestamp = System.currentTimeMillis();
        final String period = DurationFormatUtils.formatPeriod(lastTimestamp, currentTimestamp, "mm:ss.SSS");
        if (msg == null) {
            debug("[Elapsed Time]", "->", period);
        } else {
            debug("[Elapsed Time]", msg, "->", period);
        }

        lastTimestamp = currentTimestamp;
    }

    public String readLine() {
        String prompt = "Please press Enter to continue:";
        return readLine(prompt);
    }

    public String readLine(String prompt) {
        String str = null;

        if (jvmConsole == null) {
            jvmConsole = System.console();
        }

        if (jvmConsole != null) {
            str = readLineJDK6(prompt);
        } else {
            str = readLineJDK5(prompt);
        }
        return str;
    }

    private String readLineJDK5(String prompt) {
        Scanner scanner = new Scanner(System.in);
        print(prompt);
        String str = scanner.nextLine();
        print("[input]", str);
        return str;
    }

    private String readLineJDK6(String prompt) {
        if (jvmConsole == null) {
            jvmConsole = System.console();
        }
        print(prompt);
        String str = jvmConsole.readLine();
        print("[input]", str);
        return str;
    }

    private void print(Object... args) {
        //_log.info(getConsoleString(args));
        System.out.println(getConsoleString(args));
    }

}
